<template>
    <div>
        <h2 style="text-align: center;">资产借用</h2>

        <el-form label-width="180px">
            <el-form-item label="标题">
                <el-input v-model="title" placeholder=""></el-input>
            </el-form-item>

            <el-row>
                <el-col :span="12">
                    <el-form-item label="申请单号" :rules="[{ required: true, message: '申请单号为必填', trigger: 'blur' }]">
                        <el-input v-model="applicationNum" placeholder=""></el-input>
                    </el-form-item>
                </el-col>

                <el-col :span="12">

                    <el-form-item label="申请日期">
                        <el-date-picker v-model="applicationDate" type="date" format="yyyy-MM-dd" placeholder=""
                            value-format="yyyy-MM-dd"></el-date-picker>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row>
                <el-col :span="12">
                    <el-form-item label="申请人">
                        <el-select v-model="applicantId" @change="updateApplicantDepartment" placeholder="请选择申请人">
                            <el-option v-for="user in userList" :key="user.id" :label="user.name" :value="user.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>

                <el-col :span="12">
                    <el-form-item label="出借人">
                        <el-select v-model="lenderId" placeholder="请选择出借人">
                            <el-option v-for="lender in userList" :key="lender.id"
                                :label="lender.name" :value="lender.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row>
                <el-col :span="12">
                    <el-form-item label="借用日期">
                        <el-date-picker v-model="borrowDate" type="date" format="yyyy-MM-dd" placeholder=""
                            value-format="yyyy-MM-dd"></el-date-picker>
                    </el-form-item>
                </el-col>

                <el-col :span="12">

                    <el-form-item label="计划归还日期">
                        <el-date-picker v-model="planReturnDate" type="date" format="yyyy-MM-dd" placeholder=""
                            value-format="yyyy-MM-dd"></el-date-picker>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-form-item label="借用事由">
                <el-input v-model="borrowReason" placeholder=""></el-input>
            </el-form-item>
        </el-form>

        <div style="margin-top: 30px;">
            <el-button @click="assetDetailList()" type="primary">添加</el-button>
            <el-button @click="assetRemove()">移除</el-button>
        </div>
        <!--显示的数据-->
        <el-table ref="detailTable" :data="detailData" border>
            <el-table-column type="selection" width="45" align="center"></el-table-column>
            <el-table-column label="序号" align="center" width="40" type="index" :index="indexMethod">
            </el-table-column>
            <el-table-column v-if="false" prop="id"></el-table-column>
            <el-table-column prop="assetName" align="center" label="资产名称" width="130">
            </el-table-column>
            <el-table-column prop="number" label="资产编码" align="center" width="150">
            </el-table-column>
            <el-table-column prop="model" align="center" label="规格型号" width="150">
            </el-table-column>
            <el-table-column prop="assetCategoryName" align="center" label="资产分类" width="120">
            </el-table-column>
            <el-table-column prop="unit" align="center" label="单位" width="100">
            </el-table-column>
            <el-table-column prop="adminName" align="center" label="管理人" width="150">
            </el-table-column>
            <el-table-column prop="nowStorageLocationName" align="center" label="当前存放位置">
            </el-table-column>
            <el-table-column prop="targetStorageLocationName" align="center" label="借用存放位置">
            </el-table-column>
        </el-table>
        <el-button type="primary" @click="handleSubmit">提交</el-button>
        <el-button type="primary" @click="closePage">关闭</el-button>


        <!-- 全部的资产 点击添加后弹出的页面-->
        <el-dialog :visible.sync="dialogFormVisible">
            <el-form :inline="true">

                <el-form-item label="资产编码">
                    <el-input v-model="number" placeholder=""></el-input>
                </el-form-item>

                <el-form-item label="资产名称">
                    <el-input v-model="assetName" placeholder=""></el-input>
                </el-form-item>
                <el-form-item label="资产类型">
                    <el-select v-model="assetCategoryId" clearable placeholder="请选择资产类型">
                        <el-option v-for="type in assetTypeList" :key="type.id" :label="type.name" :value="type.id" />
                    </el-select>
                </el-form-item>

                <el-button type="primary" @click="fetchAssetDetailData()">查询</el-button>
                <el-button type="primary" @click="detailFlash()">重置</el-button>
            </el-form>
            <el-table ref="assetDetailTable" :data="assetDetailData" border>
                <el-table-column type="selection" width="45" align="center"></el-table-column>
                <el-table-column label="序号" align="center" width="40" type="index" :index="indexMethod">
                </el-table-column>
                <el-table-column v-if="false" prop="id">
                </el-table-column>
                <el-table-column prop="number" label="资产编码" align="center" width="120">
                </el-table-column>
                <el-table-column prop="assetName" align="center" label="资产名称" width="130">
                </el-table-column>
                <el-table-column prop="model" align="center" label="规格型号" width="120">
                </el-table-column>
                <el-table-column prop="assetCategoryName" align="center" label="资产分类" width="120">
                </el-table-column>
                <el-table-column prop="unit" align="center" label="单位" width="100">
                </el-table-column>
                <el-table-column prop="adminName" align="center" label="管理人" width="100">
                </el-table-column>
                <el-table-column prop="nowStorageLocationName" align="center" label="存放位置">
                </el-table-column>
            </el-table>

            <el-pagination @size-change="sizeAssetDetailData" @current-change="pageAssetDetailData"
                :page-sizes="[1, 5, 10, 20, 50]" :page-size="assetDetailLimit"
                layout="total, sizes, prev, pager, next, jumper" :total="assetDetailCount">
            </el-pagination>

            <div style="text-align: center; margin-top: 30px;">
                <el-button @click="handleConfirm" type="primary">确定</el-button>
                <div style="display: inline-block; width: 30px;"></div> <!-- 添加间隔 -->
                <el-button @click="dialogFormVisible = false">取消</el-button>
            </div>
        </el-dialog>
    </div>

</template>
<script>
import assetBorrowApi from "@/api/asset-borrow";
import { fixedAsset } from "@/api/fixedAsset";
import { assetCategory } from "@/api/assetCategory";
import userService from "@/api/user";
import departmentService from "@/api/depart";
import moment from 'moment';

export default {
    data() {
        return {
            tableData: [],
            page: 1,
            limit: 10,
            count: 0,
            title: '',
            applicationNum: '',
            applicationDate: '',
            applicantId: '',
            lenderId:'',
            applicantDepart: '',
            borrowDate: '',
            planReturnDate: '',
            borrowReason: '',
            remark: '',
            status: '',

            dialogFormVisible: false, // 控制弹窗的显示和隐藏
            assetDetailData: [], // 初始化资产明细数据
            assetDetailPage: 1, // 弹窗当前页
            assetDetailLimit: 10, //弹窗每页显示条数
            assetDetailCount: 0, //弹窗数据总数
            assetName: '',
            number: '',
            model: '',
            dialogTitle: '',

            assetCategoryId: '',//类型查询条件
            assetTypeList: [], //类型列表
            detailData: [], // 主表格的数据

            userList: [],  //人员列表（下拉框）
            departmentList: [], // 部门列表

            isEdit: '',
            deleteApplicationNum: '',
        }
    },

    created() {
        this.getUserList(); // 初始化时获取用户列表
        this.getDepartmentList(); // 初始化时获取部门列表
    },
    mounted() {
        // 获取查询参数
        const query = this.$route.query;

        if (query.applicationNum) {
            this.isEdit = 'edit';
            this.applicationNum = query.applicationNum;
            this.deleteApplicationNum = query.applicationNum;  //删除的单号，保证了不会跟随输入框中的值而变动
            this.title = query.title;
            // 如果后端返回的是字符串格式，需将其转换为 Date 对象
            this.applicationDate = query.applicationDate ? new Date(query.applicationDate) : null;
            this.applicantId = query.applicationPerson;
            this.lenderId = query.lenderPerson;
            this.borrowDate = query.borrowDate ? new Date(query.borrowDate) : null;
            this.borrowReason = query.borrowReason;
            this.planReturnDate = query.planReturnDate ? new Date(query.planReturnDate) : null;
            this.fetchAssetDetail();

        } else {
            this.isEdit = '';// 新增模式
        }
    },

    methods: {
        setApplicantId() {
            console.log(this.userList)
            // 确保用户列表是加载完成的
            if (this.userList.length > 0) {
                // 查找与申请人姓名匹配的用户
                console.log("bbbbbbb")
                const selectedUser = this.userList.find(user => user.name === this.query.applicationPerson); // 假设 user 对象中有 name 属性
                if (selectedUser) {
                    console.log("aaaaaaa")
                    // 设置申请人 ID
                    this.applicantId = selectedUser.id; // 将对应的用户 ID 赋值给 applicantId
                    this.applicantDepart = selectedUser.departId; // 设置申请部门，如果有的话
                }
            }
        },
        getAssetTypeList() {
            assetCategory.findAll().then(response => {
                this.assetTypeList = response.data
            })
        },
        getUserList() {
            userService.findAll().then(response => {
                this.userList = response.data;
            });
        },

        getDepartmentList() {
            departmentService.findAll().then(response => {
                this.departmentList = response.data;
            });
        },


        //修改的表单页面回显数据
        fetchData() {
            assetBorrowApi.findByApplicationNum({
                applicationNum: this.applicationNum,
            }).then(response => {
                this.detailData = response.data;
            }).catch(error => {
                console.error("获取数据失败:", error);  // 捕获和打印错误
            });
        },

        //返回
        closePage() {
            this.$router.go(-1); // 返回到之前的页面
        },

        //添加数据
        handleSubmit() {

            if (this.applicationNum === '') {
                this.$message.warning("请输入单号！");
                return;
            }
            // 检查是否有数据
            if (this.detailData.length === 0) {
                this.$message.warning("请至少添加一项资产数据进行提交！");
                return;
            }

            // 构建要提交的数据
            const submitData = this.detailData.map(row => {
                return {
                    assetId: row.id, // 假设每行数据有一个 id 属性
                    title: this.title,
                    applicationNum: this.applicationNum,
                    applicationDate: this.applicationDate,
                    applicantId: this.applicantId,
                    lenderId: this.lenderId,
                    borrowDate: this.borrowDate,
                    planReturnDate: this.planReturnDate,
                    borrowReason: this.borrowReason,
                };
            });

            const submitAction = this.isEdit === 'edit'
                ? assetBorrowApi.deleteByApplicationNum({ applicationNum: this.deleteApplicationNum })
                : Promise.resolve(); // 如果不是编辑模式，直接返回已解决的 Promise

            submitAction
                .then(() => {
                    // 提交数据给后端
                    return assetBorrowApi.addBatch(submitData);
                })
                .then(response => {
                    this.$message.success("提交成功！");
                    this.$router.go(-1);
                })
                .catch(error => {
                    console.error("提交失败:", error);
                    this.$message.error("该单号资产可能已经借出，请重试。");
                });
        },


        updateApplicantDepartment() {
            // 当选择申请人时，根据申请人更新对应的申请部门
            const selectedUser = this.userList.find(user => user.id === this.applicantId);
            if (selectedUser) {
                this.applicantDepart = selectedUser.departId; // 假设用户对象中有 departmentId 属性
            } else {
                this.applicantDepart = ''; // 若未找到，则清空
            }
        },


        //资产明细
        assetDetailList() {

            // 打开弹窗
            this.dialogFormVisible = true;

            //获取类型列表（下拉框）
            this.getAssetTypeList();

            // 请求资产明细数据
            this.fetchAssetDetailData();
        },

        fetchAssetDetailData() {
            fixedAsset.list({
                page: this.assetDetailPage, // 使用当前页码
                limit: this.assetDetailLimit, // 使用每页条数
                name: this.assetName,
                number: this.number,
                assetCategoryId: this.assetCategoryId
            }).then(response => {
                this.assetDetailData = response.data; // 资产明细数据
                this.assetDetailCount = response.count; // 总数
            }).catch(error => {
                console.error("获取资产明细失败:", error);
                this.$message.error("获取资产明细失败，请重试。");
            });
        },

        //修改界面回显主表格数据
        fetchAssetDetail() {
            assetBorrowApi.assetList({
                page: 1, // 页码
                limit: 100, // 每页条数
                applicationNum: this.applicationNum
            }).then(response => {
                if (response.data && Array.isArray(response.data)) {
                    this.detailData = response.data.map(item => ({
                        id: item.id, // 假设后端有 id 字段
                        assetName: item.assetName || '', // 映射资产名称
                        number: item.number || '', // 映射资产编码
                        model: item.model || '', // 映射规格型号
                        assetCategoryName: item.assetCategoryName || '', // 映射资产分类
                        unit: item.unit || '', // 映射单位
                        adminName: item.adminName || '', // 映射管理人
                        userName: item.userName || '', // 映射使用人
                        nowStorageLocationName: item.nowStorageLocationName || '', // 映射当前存放位置
                        targetStorageLocationName: item.targetStorageLocationName || '' // 映射退库存放位置
                    }));
                }
            }).catch(error => {
                console.error("获取资产明细失败:", error);
                this.$message.error("获取资产明细失败，请重试。");
            });
        },


        sizeData(size) {
            this.limit = size
            this.fetchData()
        },
        pageData(page) {
            this.page = page
            this.fetchData()
        },

        // 资产明细分页大小变化
        sizeAssetDetailData(size) {
            this.assetDetailLimit = size; // 更新分页大小
            this.assetDetailPage = 1; // 重置为第一页
            this.fetchAssetDetailData(); // 请求新的数据
        },

        // 资产明细页码变化
        pageAssetDetailData(page) {
            this.assetDetailPage = page; // 更新当前页
            this.fetchAssetDetailData(); // 请求新的数据
        },
        detailFlash() {
            this.number = '';
            this.assetName = '';
            this.model = '';
        },



        //增加一个格式化日期的方法
        dataFormat(row, column) {

            let date = row[column.property]

            if (date == undefined) {
                return ''
            }

            return moment(date).format('YYYY-MM-DD hh:mm:ss')
        },

        indexMethod(index) {
            return index + 1;
        },

        handleClick(row) {
            console.log(row);
        },

        handleConfirm() {
            // 获取选中的行数据
            const selectedRows = this.$refs.assetDetailTable.selection;

            // 处理选中的数据
            if (selectedRows.length > 0) {
                this.detailData.push(...selectedRows.map(row => ({ ...row }))); // 使用扩展运算符进行数组合并
            } else {
                this.$message.warning("请至少选择一项数据！");
            }

            this.dialogFormVisible = false;
        },

        //移除选择的主表格数据
        assetRemove() {
            // 获取选中的行数据
            const selectedRows = this.$refs.detailTable.selection; // 确保在主表格上设置了 ref="detailTable"

            // 处理选中的数据
            if (selectedRows.length > 0) {
                // 从 detailData 中移除选中的行
                this.detailData = this.detailData.filter(row => !selectedRows.includes(row));
            }
        },

        //将状态从数字显示为对应的值
        formatStatus(row) {
            switch (String(row.status)) {
                case '1':
                    return '草稿';
                case '2':
                    return '审核中';
                case '3':
                    return '驳回';
                case '4':
                    return '已办结';
                default:
                    return '审核中';
            }
        }
    }
}
</script>